<template>
  <div class="job-management">
    <el-card>
      <div slot="header" class="card-header">
        <span>职位管理</span>
        <el-button type="primary" size="small" @click="handleAdd">发布职位</el-button>
      </div>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="职位名称">
          <el-input v-model="searchForm.name" placeholder="请输入职位名称"></el-input>
        </el-form-item>
        <el-form-item label="公司名称">
          <el-input v-model="searchForm.companyName" placeholder="请输入公司名称"></el-input>
        </el-form-item>
        <el-form-item label="工作地点">
          <el-select v-model="searchForm.address" placeholder="请选择">
            <el-option label="全部" value=""></el-option>
            <el-option :label="item" :value="item" v-for="item, index in addressList" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择">
            <el-option label="全部" value=""></el-option>
            <el-option label="正常" :value="1"></el-option>
            <el-option label="禁用" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 职位列表 -->
      <el-table :data="jobList" border style="width: 100%">
        <el-table-column prop="name" label="职位名称" width="150"></el-table-column>
        <el-table-column prop="companyName" label="公司名称"></el-table-column>
        <el-table-column prop="address" label="地点"></el-table-column>
        <el-table-column prop="type" label="类型" width="100"></el-table-column>
        <el-table-column prop="category" label="分类" width="100"></el-table-column>
        <el-table-column prop="salary" label="薪资" width="120"></el-table-column>
        <el-table-column prop="experience" label="经验要求" width="100"></el-table-column>
        <el-table-column prop="education" label="学历要求" width="100"></el-table-column>
        <el-table-column prop="createTime" label="发布时间" width="180"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">
              {{ scope.row.status == 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="examineStatus" label="审核状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.examineStatus)">
            {{ getStatusText(scope.row.examineStatus) }}
          </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row, 2)"
              v-if="scope.row.status == 1">删除</el-button>
            <el-button size="mini" type="success" @click="handleDelete(scope.row, 1)" v-else>恢复</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑职位弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
      <el-form :model="jobForm" ref="jobForm" label-width="100px">
        <el-form-item label="职位名称" prop="name">
          <el-input v-model="jobForm.name" placeholder="请输入职位名称"></el-input>
        </el-form-item>
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="jobForm.companyName" placeholder="请输入公司名称"></el-input>
        </el-form-item>
        <el-form-item label="工作地点" prop="address">
          <el-select v-model="jobForm.address" placeholder="请选择">
            <el-option :label="item" :value="item" v-for="item, index in addressList" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="薪资范围" prop="salary">
          <el-input v-model="jobForm.salary" placeholder="请输入薪资范围，如：15k-25k"></el-input>
        </el-form-item>
        <el-form-item label="职位类型" prop="type">
          <el-input v-model="jobForm.type" placeholder="请输入职位类型"></el-input>
        </el-form-item>
        <el-form-item label="职位分类" prop="category">
          <el-select v-model="jobForm.category" placeholder="请选择职位分类">
            <el-option label="正式" value="正式"></el-option>
            <el-option label="实习" value="实习"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="经验要求" prop="experience">
          <el-select v-model="jobForm.experience" placeholder="请选择">
            <el-option label="应届生" value="应届生"></el-option>
            <el-option label="1-3年" value="1-3年"></el-option>
            <el-option label="3-5年" value="3-5年"></el-option>
            <el-option label="5年以上" value="5年以上"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学历要求" prop="education">
          <el-select v-model="jobForm.education" placeholder="请选择">
            <el-option label="大专" value="大专"></el-option>
            <el-option label="本科" value="本科"></el-option>
            <el-option label="硕士" value="硕士"></el-option>
            <el-option label="博士" value="博士"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职位描述" prop="introduce">
          <el-input type="textarea" v-model="jobForm.introduce" :rows="4" placeholder="请输入职位描述"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getJobAdminList, getJobSubmit, getJobTypeList } from '@/api'
import { MessageBox } from 'element-ui'

export default {
  name: 'JobManagement',
  data() {
    return {
      searchForm: {
        title: '',
        company: '',
        location: '',
        status: ''
      },
      currentPage: 1,
      pageSize: 10,
      total: 0,
      jobList: [],
      dialogVisible: false,
      dialogType: 'add',
      dialogTitle: '发布职位',
      jobForm: {
        title: '',
        company: '',
        location: '',
        salary: '',
        experience: '',
        education: '',
        description: '',
        requirements: ''
      },
      addressList: [
        // 直辖市
        "北京", "上海", "天津", "重庆",
        // 广东省
        "广州", "深圳", "东莞", "佛山", "珠海", "中山", "惠州", "汕头", "江门", "湛江", "肇庆", "茂名",
        // 江苏省
        "南京", "苏州", "无锡", "常州", "南通", "徐州", "扬州", "盐城", "泰州", "镇江", "淮安", "连云港", "宿迁",
        // 浙江省
        "杭州", "宁波", "温州", "绍兴", "嘉兴", "金华", "台州", "湖州", "衢州", "丽水", "舟山",
        // 四川省
        "成都", "绵阳", "宜宾", "南充", "德阳", "泸州", "达州", "乐山", "眉山", "内江", "自贡", "攀枝花",
        // 湖北省
        "武汉", "宜昌", "襄阳", "荆州", "黄冈", "孝感", "十堰", "荆门", "鄂州", "咸宁", "随州",
        // 山东省
        "济南", "青岛", "烟台", "潍坊", "临沂", "淄博", "济宁", "泰安", "威海", "德州", "聊城", "菏泽", "日照", "枣庄",
        // 福建省
        "福州", "厦门", "泉州", "漳州", "莆田", "宁德", "三明", "南平", "龙岩",
        // 河南省
        "郑州", "洛阳", "南阳", "许昌", "周口", "新乡", "商丘", "驻马店", "信阳", "安阳", "开封", "平顶山",
        // 湖南省
        "长沙", "株洲", "湘潭", "衡阳", "岳阳", "常德", "邵阳", "郴州", "益阳", "永州", "怀化", "娄底", "张家界",
        // 其他省份重点城市
        // 河北省
        "石家庄", "保定", "唐山", "邯郸", "廊坊", "沧州", "邢台", "秦皇岛", "衡水", "张家口",
        // 陕西省
        "西安", "咸阳", "宝鸡", "渭南", "汉中", "榆林", "延安", "安康", "商洛",
        // 辽宁省
        "沈阳", "大连", "鞍山", "抚顺", "锦州", "营口", "盘锦", "丹东", "辽阳", "本溪",
        // 其他地区
        "合肥（安徽）", "芜湖（安徽）", "南昌（江西）", "赣州（江西）",
        "太原（山西）", "大同（山西）", "呼和浩特（内蒙古）", "包头（内蒙古）",
        "南宁（广西）", "柳州（广西）", "桂林（广西）", "海口（海南）", "三亚（海南）",
        "贵阳（贵州）", "遵义（贵州）", "昆明（云南）", "曲靖（云南）",
        "兰州（甘肃）", "天水（甘肃）", "银川（宁夏）", "西宁（青海）",
        "乌鲁木齐（新疆）", "克拉玛依（新疆）", "拉萨（西藏）",
        // 港澳台
        "香港", "澳门", "台北（台湾）", "高雄（台湾）", "台中（台湾）", "新北（台湾）"
      ]
    }
  },
  created() {
    this.fetchJobList()
  },
  methods: {
    getStatusType(status) {
      const statusMap = {
        '1': 'warning',
        '2': 'success',
        '3': 'danger'
      }
      return statusMap[status]
    },
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        '1': '待审核',
        '2': '已通过',
        '3': '已拒绝'
      }
      return statusMap[status]
    },
    async fetchJobList() {
      try {
        const params = {
          currPage: this.currentPage,
          pageSize: this.pageSize,
          ...this.searchForm
        }
        const res = await getJobAdminList(params)
        if (res.code === 200) {
          this.jobList = res.data.list
          this.total = parseInt(res.data.total) || 0
        } else {
          this.$message.error(res.message || '获取职位列表失败')
        }
      } catch (error) {
        console.error('获取职位列表失败:', error)
        this.$message.error('获取职位列表失败')
      }
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchJobList()
    },
    resetSearch() {
      this.searchForm = {
        title: '',
        company: '',
        location: '',
        status: ''
      }
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchJobList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchJobList()
    },
    handleAdd() {
      this.dialogType = 'add'
      this.dialogTitle = '发布职位'
      this.jobForm = {
        title: '',
        company: '',
        location: '',
        salary: '',
        experience: '',
        education: '',
        description: '',
        requirements: ''
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogType = 'edit'
      this.dialogTitle = '编辑职位'
      this.jobForm = { ...row }
      this.dialogVisible = true
    },
    handleDelete(row, status) {
      MessageBox.confirm('确认执行这种操作吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          var data = row;
          data.status = status;
          getJobSubmit(data).then(res => {
            this.$message.success('操作成功')
            this.fetchJobList();
          }).catch(err => {
            this.$message.error(err.msg);
          })
        } catch (error) {
          this.$message.error('操作失败')
        }
      }).catch(() => { })
    },
    handleToggleStatus(row) {
      const newStatus = row.status === 'active' ? 'closed' : 'active'
      const actionText = newStatus === 'active' ? '重新发布' : '结束招聘'
      MessageBox.confirm(`确认${actionText}该职位吗？`, '提示', {
        type: 'warning'
      }).then(async () => {
        try {

          this.$message.success(`${actionText}成功`)
          this.fetchJobList()
        } catch (error) {
          console.error(`${actionText}职位失败:`, error)
          this.$message.error(`${actionText}职位失败`)
        }
      }).catch(() => { })
    },
    handleSubmit() {
      this.$refs.jobForm.validate(async valid => {
        if (valid) {
          try {
            getJobSubmit(this.jobForm).then(res => {
              this.$message.success('职位提交成功');
              this.fetchJobList();
              this.dialogVisible = false;
            }).catch(err => {
              this.dialogVisible = false;
              this.$message.error(err.msg);
            })
          } catch (error) {
            console.error(this.dialogType === 'add' ? '发布职位失败:' : '更新职位失败:', error)
            this.$message.error(this.dialogType === 'add' ? '发布职位失败' : '更新职位失败')
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
.job-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>